import { onBeforeUnmount, unref } from 'vue'
import { MaybeRef, Pausable, useRafFn } from '@vueuse/core'

interface ScrollElement {
  scrollTop: number
  style: CSSStyleDeclaration
}

export function scroller(el: MaybeRef<ScrollElement>, d: number, onStart: Function, onEnd?: Function) {
  let raf: Pausable
  onBeforeUnmount(() => raf?.pause())

  const ret = {
    transiting: false,
    scroll
  }

  function scroll(option: { x?: number, y: number }) {
    ret.transiting = true
    const t = Date.now()
    const _el = unref(el)
    const sy = _el.scrollTop, offset = option.y - sy
    ret.transiting = true
    _el.style.scrollBehavior = 'unset'
    onStart?.()
    raf?.pause()
    raf = useRafFn(() => {
      const r = Math.min((Date.now() - t) / d, 1)
      _el.scrollTop = sy + offset * r
      if (r >= 1) {
        _el.style.scrollBehavior = ''
        raf.pause()
        ret.transiting = false
        onEnd?.()
      }
    })
  }

  return ret
}